<template>
  <span class="wrap" @click="clickSendCode()">
    <el-button v-if="showSendBtn" class="button-login" type="primary">{{ getText }}</el-button>
    <el-button v-else type="info" class="button-login" disabled>{{count}}s后重新发送</el-button>
  </span>
</template>

<script>
const TIME_COUNT = 60;
import { registerSendCode, getSendSms } from '@/api/login' // 注册的验证码
  export default {
    props: ['type', 'phone', 'params'],
    components: {

    },
    data() {
      return {
        showSendBtn: true,
        count: '',
        getText: '获取验证码',
        timer: null,
      }
    },
    created() {

    },
    methods: {
      // 发送成功处理
      sendSuccess(res) {
        if(res.code == 200 || res.data.code == 200){
         this.sendTimeDown();
         this.$message.success('提示：已发送至'+ this.params +'，请注意查收!');
        }
      },
      // 点击发送验证码
      clickSendCode(){
        // 如果需要验证是否有手机号码 或填写了手机号码
        if(!this.params){
          return this.$message({
            type: 'warning',
            message: `请填写手机号码`
          })
        }else if (this.params !== '') {
            var reg=/^1[3456789]\d{9}$/;
            if(!reg.test(this.params)){
              return;
            }
          }

        if(this.showSendBtn == false){
          return false
        }

        // 注册 验证码
        if(this.type == 'register'){
          registerSendCode({"mobile": this.params, "codeType": 1}).then(res => {
            this.sendSuccess(res)
          })
        }else if(this.type == 'login'){
          getSendSms({ "moblie": this.params }).then(res => {
            this.sendSuccess(res)
          })
        }


      },
      // 验证码倒计时
      sendTimeDown() {
        if (!this.timer) {
          this.count = TIME_COUNT;
          this.showSendBtn = false;
          this.timer = setInterval(() => {
            if (this.count > 0 && this.count <= TIME_COUNT) {
              this.count--;
            } else {
              this.showSendBtn = true;
              clearInterval(this.timer);
              this.timer = null;
              this.getText = '重新获取'
            }
          }, 1000)
        }
      },

      vcodeCallback(phone) {
        this.$emit('vcodeCallback', phone);
      }
    }
  }
</script>

<style lang="scss">
.getVcode{
  width: 120px;
  .is-disabled{
    background-color: #c8c9cc;
  }
}
  .button-login{
    width: 130px !important;
    margin-left: 10px;
    background-color: #255B8B;
    border-color: #255B8B;
    transition: all .3s;
  &:hover{
    opacity: .9;
    background-color: #255B8B;
    border-color: #255B8B;
  }
}
</style>
